package org.example.controller;

import com.alibaba.fastjson2.JSONObject;
import org.example.mapper.CKUserMapper;
import org.example.mapper.UserMapper;
import org.example.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    UserMapper userMapper;

    @Autowired
    CKUserMapper ckUserMapper;

    @GetMapping("/hello")
    public String helloWorld() {
        return "hello world";
    }

    @GetMapping("/get/{id}")
    public String getUserById(@PathVariable("id") Long id) {
        User user = userMapper.getById(id);
        return JSONObject.toJSONString(user);
    }

    @GetMapping("/ck/get/{id}")
    public String getCKUserById(@PathVariable("id") Long id) {
        User user = ckUserMapper.getById(id);
        return JSONObject.toJSONString(user);
    }

    @GetMapping("/save/{name}")
    public String randomUser(@PathVariable("name") String name) {
        User user = generateUser(name);
        userMapper.saveUser(user);
        return user.getId().toString();
    }

    @GetMapping("/ck/save/{name}")
    public String ckRandomUser(@PathVariable("name") String name) {
        User user = generateUser(name);
        ckUserMapper.saveUser(user);
        return user.getId().toString();
    }

    private User generateUser(String name) {
        User user = new User();
        long id = System.nanoTime() / 1000L;
        user.setId(id);
        user.setName(name);
        Random rd = new Random();
        long birth = rd.nextLong(id);
        user.setGender(birth % 2 == 0);
        user.setBirth(new Date(birth));
        user.setCreateTime(new Date());
        return user;
    }
}
